import {
  checkIsSoterEnrolledInDevice,
  checkIsSupportSoterAuthentication,
  showToast,
  startSoterAuthentication,
  useEffect,
  useState
} from '@tarojs/taro';
import { View, Block } from '@tarojs/components';

const BioCore = ({ onAuth, onReadBios, isAuth, isAutoAuth }) => {
  const [isReadedBios, setIsReadedBios] = useState(false);
  const [bios, setBios] = useState([]);
  const biosLabel = {
    fingerPrint: '指纹识别',
    facial: '人脸识别',
    speech: '声纹识别'
  };
  useEffect(() => {
    if (isAuth) {
      checkIsSupportSoterAuthentication()
        .then(({ supportMode = [] }) => {
          const bs = supportMode.map((x) => ({ text: biosLabel[x], value: x }));
          setIsReadedBios(true);
          setBios(bs);
          onReadBios(bs);
          if (!supportMode.length) {
            onAuth(-1, '您的设备不支持生物认证');
          } else if (supportMode.length === 1) {
            onChange({ detail: { value: supportMode[0] } });
          } else if (supportMode.length > 1) {
            if (isAutoAuth) {
              onChange({
                detail: { value: supportMode.includes('facial') ? 'facial' : supportMode[0] }
              });
            } else {
              onAuth(2, '选择生物认证模式');
            }
          }
        })
        .catch(() => {
          if (__wxConfig['envVersion'] === 'develop') {
            onAuth(1, '开发工具强制中认证成功');
            return;
          }
          const msg = '读取设备生物认证失败';
          onAuth(0, msg);
          showToast({ title: msg, icon: 'none' });
        });
    }
  }, [isAuth]);

  const onAuthCore = ({ type }) => {
    checkIsSoterEnrolledInDevice({ checkAuthMode: type })
      .then((res) => {
        const { isEnrolled, errMsg } = res;
        if (isEnrolled) {
          startSoterAuthentication({
            requestAuthModes: [type],
            challenge: new Date().getTime() + '',
            authContent: `请使用${biosLabel[type]}解锁`
          })
            .then((res) => {
              console.log('开始生物认证', res);
              onAuth(1, '认证成功');
            })
            .catch((error) => {
              console.error(error);
              const msg = '生物验证失败,' + error.errMsg;
              showToast({ title: msg, icon: 'none' });
              onAuth(0, msg);
            });
        } else {
          onAuth(0, '生物验证失败,' + errMsg);
        }
      })
      .catch((error) => {
        const msg = '生物验证失败,' + error.errMsg;
        showToast({ title: msg, icon: 'none' });
        onAuth(0, msg);
      });
  };

  const onChange = (e) => {
    const value = e.detail.value;
    onAuthCore({ type: value });
  };

  return <Block></Block>;
};
BioCore.defaultProps = {
  isAuth: false,
  isAutoAuth: true,
  onAuth: () => {},
  onReadBios: () => {}
};
export default BioCore;
